<script setup lang="jsx">
import { UUID } from 'uuidjs';
import { computed, onUnmounted, ref, watch } from 'vue';
import { Empty } from 'ant-design-vue';
import { getTableData } from '@/service/api/modules/collection-management/borehole-data';
import { useDictStore } from '@/store/modules/dict';
import SearchBox from './modules/search.vue';
import StateChart from './modules/state-chart.vue';
import Details from './modules/details.vue';

const { getDict } = useDictStore();
const stateList = ref([]);
getDict('drilling_equipment_state').then(dict => {
  stateList.value = dict;
});

const simpleImage = Empty.PRESENTED_IMAGE_SIMPLE;

const searchParams = ref({
  subEqpName: null,
  pgmPathName: null
});
const leftTableData = ref([]);
const loading = ref(false);
const olaList = ref([]);

const leftTableLoading = ref(false);
// setDefaultDateRange();
function getLeftTableData() {
  leftTableLoading.value = true;
  getTableData(searchParams.value)
    .then(({ data, error }) => {
      if (!error) {
        data?.forEach((item, index) => {
          item.index = index + 1;
          item.TUuid = UUID.generate();
        });
        leftTableData.value = data;
        olaList.value = data;
      }
    })
    .finally(() => (leftTableLoading.value = false));
}

getLeftTableData();

function filterArr(cb) {
  // 取出数据
  const arr = olaList.value.filter(item => cb(item));
  // 重新循环序号排序
  // arr?.forEach((item, index) => {
  //   item.index = index + 1;
  // });
  return arr;
}

function getSearchTableData() {
  if (!searchParams.value.subEqpName && !searchParams.value.pgmPathName) {
    return olaList.value;
  }

  if (searchParams.value.subEqpName && searchParams.value.pgmPathName) {
    return filterArr(
      item =>
        item?.subEqpName?.includes(searchParams.value.subEqpName) &&
        item?.pgmPath?.includes(searchParams.value.pgmPathName)
    );
  }

  if (searchParams.value.subEqpName) {
    return filterArr(item => item?.subEqpName?.includes(searchParams.value.subEqpName));
  }

  if (searchParams.value.pgmPathName) {
    return filterArr(item => item?.pgmPath?.includes(searchParams.value.pgmPathName));
  }
  return [];
}

function search() {
  leftTableData.value = getSearchTableData();
}

let searchTimer = null;
watch(
  () => searchParams.value,
  () => {
    if (searchTimer) return;
    searchTimer = setTimeout(() => {
      clearTimeout(searchTimer);
      searchTimer = null;
      search();
    }, 500);
  },
  { deep: true }
);

let timer = setInterval(
  () => {
    getLeftTableData();
  },
  1000 * 60 * 5 // 5分钟刷新一次
);

function reset() {
  leftTableData.value = olaList.value;
}

function progressFormat(percent) {
  if (Number(percent) >= 100) {
    return '完成';
  }
  return `${percent}%`;
}

const deviceCount = computed(() => {
  const num = olaList.value.length.toString().padStart(3, '0');
  return num.split('');
});

const ColorArr = {
  WORK: '#1CD66C',
  WAIT: '#8e9dff',
  ALARM: '#FF3030',
  IDLE: '#26deca',
  STOP: '#fedc69'
};
const currentItem = ref(null);
const { updateModalOptions, handleShow } = window.$useModal({
  modalOption: {
    title: '设备详情',
    showConfirmBtn: false,
    confirmBtnText: '关闭',
    destroyOnClose: true,
    width: '955px'
  },
  component: () => <Details v-model:data={currentItem.value} />
});

function handleDetail(item) {
  updateModalOptions({
    title: `${item.subEqpName}设备详情`
  });
  currentItem.value = item;
  handleShow();
}

onUnmounted(() => {
  clearInterval(timer);
  timer = null;
});
</script>

<template>
  <div class="borehole-data-page h-full w-full flex">
    <div class="left-list min-h-500px flex-col-stretch gap-5px overflow-hidden lt-sm:overflow-auto">
      <SearchBox v-model:model="searchParams" @reset="reset" @search="search" />
      <div class="list h-full w-full overflow-auto">
        <ASpin tip="数据加载中..." :spinning="loading" class="h-full w-full">
          <div v-if="leftTableData.length" class="row flex flex-wrap">
            <!--  :md="24" :lg="12" :xl="8" :xxl="4.8" -->
            <div v-for="(item, index) in leftTableData" :key="index" class="col col-md-24 col-lg-8 col-xxl-4_8">
              <div
                class="card"
                :style="{
                  border: `2px solid ${ColorArr[item.equipmentStatus]}`
                }"
              >
                <div class="device-data">
                  <div class="data">
                    <div class="label">设备名称</div>
                    <div class="value" :title="item.subEqpName">{{ item.subEqpName }}</div>
                  </div>
                  <div class="data">
                    <div class="label">时 间</div>
                    <div class="value" :title="item.dateTime">{{ item.dateTime }}</div>
                  </div>
                  <div class="data">
                    <div class="label">稼动率</div>
                    <div class="value" :title="item.duty">{{ item.duty }}</div>
                  </div>

                  <div class="data">
                    <div class="label">开机时间</div>
                    <div class="value" :title="item.startTime">{{ item.shiftOperateTime }}</div>
                  </div>
                  <div class="data">
                    <div class="label">加工时间</div>
                    <div class="value" :title="item.lotRunTime">{{ item.lotRunTime }}</div>
                  </div>
                </div>
                <!--
 <div class="charts flex flex-center">
                  <AProgress
                    stroke-linecap="square"
                    :percent="Number(item.runPresent)"
                    type="dashboard"
                    title="程序加工百分数"
                    :size="[80, 80]"
                    :format="progressFormat"
                    :stroke-color="{ '0%': '#87d068', '100%': '#108ee9' }"
                  />
                </div>
-->
                <div class="view-device-data cursor-pointer color-#646cff" @click="handleDetail(item)">查看详情</div>
                <div class="state w-full">
                  <div class="data flex">
                    <div class="label font-bold">轴开启状态</div>
                    <div class="value flex gap-3px color-#646cff">
                      <span
                        v-for="(i, idx) in item.axisStatus?.split('')"
                        :key="idx"
                        class="pl-3px pr-3px"
                        :class="Number(i) === 1 ? 'bg-green' : 'bg-#eee'"
                      >
                        {{ idx + 1 }}
                      </span>
                    </div>
                  </div>
                  <div class="data">
                    <div class="label">加工进度</div>
                    <div class="value progress w-full">
                      <AProgress
                        :percent="Number(item.runPresent)"
                        :format="progressFormat"
                        :stroke-color="{ '0%': '#87d068', '100%': '#108ee9' }"
                      />
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <template v-else>
            <AEmpty :image="simpleImage" />
          </template>
        </ASpin>
      </div>
    </div>
    <div class="right-msg">
      <div class="right-card bg-#fff pb-30px pt10px">
        <div class="angle">
          <div class="left-top"></div>
          <div class="right-top"></div>
          <div class="left-bottom"></div>
          <div class="right-bottom"></div>
        </div>
        <div class="card-title">设备总数</div>
        <div class="card-content flex flex-center gap-15px">
          <!-- <CountTo :start-value="0" :end-value="leftTableData.length" class="device-count text-30px dark:text-dark" /> -->
          <CountTo
            v-for="(item, index) in deviceCount"
            :key="index"
            :start-value="0"
            :end-value="Number(item)"
            class="device-count text-30px dark:text-dark"
          />
        </div>
      </div>
      <div class="right-card mt15px bg-#fff pb-30px pt10px">
        <div class="angle">
          <div class="left-top"></div>
          <div class="right-top"></div>
          <div class="left-bottom"></div>
          <div class="right-bottom"></div>
        </div>
        <div class="card-content">
          <StateChart :list="olaList"></StateChart>
        </div>
      </div>
      <div class="right-card mt15px bg-#fff pb-30px pl10px pt15px">
        <div class="angle">
          <div class="left-top"></div>
          <div class="right-top"></div>
          <div class="left-bottom"></div>
          <div class="right-bottom"></div>
        </div>
        <div class="card-content">
          <div class="card-title">左侧设备状态说明</div>
          <div v-for="(item, index) in stateList" :key="index" class="card-instructions flex-center justify-start">
            边框为
            <div class="equipment-status type h-14px w-14px" :class="item.value"></div>
            <div class="text">代表{{ item.label }}的设备</div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.borehole-data-page {
  .left-list {
    width: calc(100% - 350px);
  }
  .list {
    :deep(.ant-spin-nested-loading) {
      width: 100%;
      height: 100%;
      .ant-spin-container {
        width: 100%;
        height: 100%;
      }
      .ant-row {
        margin: 0 !important;
      }
    }

    .row {
      row-gap: 6px;
      .col {
        padding-left: 3px;
        padding-right: 3px;
      }

      @media (min-width: 768px) {
        .col-md-24 {
          display: block;
          flex: 0 0 100%;
          max-width: 100%;
        }
      }

      @media (min-width: 992px) {
        .col-lg-8 {
          display: block;
          flex: 0 0 33.333333%;
          max-width: 33.333333%;
        }
      }

      @media (min-width: 1200px) {
        .col-xl-6 {
          display: block;
          flex: 0 0 25%;
          max-width: 25%;
        }
      }

      @media (min-width: 1600px) {
        .col-xxl-4_8 {
          display: block;
          flex: 0 0 20%;
          max-width: 20%;
        }
      }
    }

    .card {
      // cursor: pointer;
      position: relative;
      width: 100%;
      box-shadow: 0 0 10px 1px rgba(128, 128, 128, 0.2);
      border-radius: 10px;
      background: #fff;
      display: flex;
      flex-wrap: wrap;
      padding: 15px;
      padding-right: 5px;
      .device-data,
      .state {
        // width: 225px;
        width: calc(100% - 90px);
        width: 100%;
        // border-right: 1px solid #eee;
        padding-right: 8px;
        font-size: 13px;
        .data {
          display: flex;
          .label {
            font-weight: bold;
            padding-right: 5px;
            min-width: 79px;
            text-align-last: justify;
            &::after {
              content: ':';
            }
          }
          .value {
            // color: #888;
            white-space: nowrap; /* 防止文本换行 */
            overflow: hidden; /* 隐藏溢出的内容 */
            text-overflow: ellipsis;
            &.progress {
              :deep(.ant-progress-line) {
                margin-bottom: 0;
              }
            }
          }
        }
      }
      .state {
        width: 100% !important;
      }
      .charts {
        width: 90px;
        // width: calc(100% - 225px);
        margin-top: 8px;
        .title {
          width: 100%;
          font-weight: bold;
        }
      }
      .view-device-data {
        position: absolute;
        top: 0px;
        right: 5px;
      }
    }
  }
  .right-msg {
    width: 350px;
    padding: 8px;
    .right-card {
      position: relative;
      .angle {
        position: absolute;
        width: 100%;
        height: 100%;
        top: 0;
        left: 0;
        // z-index: -1;
        .left-top {
          position: absolute;
          width: 15px;
          height: 15px;
          background: transparent;
          border-top: 3px solid #646cff;
          border-left: 3px solid #646cff;
          z-index: 99;
        }
        .right-top {
          top: 0;
          right: 0;
          position: absolute;
          width: 15px;
          height: 15px;
          background: transparent;
          border-top: 3px solid #646cff;
          border-right: 3px solid #646cff;
          z-index: 99;
        }
        .left-bottom {
          bottom: 0;
          left: 0;
          position: absolute;
          width: 15px;
          height: 15px;
          background: transparent;
          border-bottom: 3px solid #646cff;
          border-left: 3px solid #646cff;
          z-index: 99;
        }
        .right-bottom {
          bottom: 0;
          right: 0;
          position: absolute;
          width: 15px;
          height: 15px;
          background: transparent;
          border-bottom: 3px solid #646cff;
          border-right: 3px solid #646cff;
          z-index: 99;
        }
      }
    }
    .card-title {
      font-size: 28px;
      text-align: center;
      color: #646cff;
      font-weight: bold;
    }
    .card-content {
      .device-count {
        width: 50px;
        height: 50px;
        line-height: 50px;
        text-align: center;
        font-size: 48px;
        font-weight: 700;
        font-family: 'Arial', sans-serif;
        color: #1d26c0;
        border: 1px solid #d0d0d6;
        box-shadow: 1px 1px 4px 2px #d0d0d6;
      }
      .card-instructions {
        line-height: 30px;
        .equipment-status {
          &.WORK {
            background-color: #1cd66c;
          }
          &.WAIT {
            background-color: #8e9dff;
          }
          &.ALARM {
            background-color: #ff3030;
          }
          &.IDLE {
            background-color: #26deca;
          }
          &.STOP {
            background-color: #fedc69;
          }
        }
      }
    }
  }
}

@media (min-width: 1600px) {
  :where(.css-dev-only-do-not-override-1qjex96).ant-col-xxl-4 {
    display: block;
    flex: 0 0 16.666666666666664%;
    max-width: 16.666666666666664%;
  }
}
</style>
